import httpService, { RequestParam } from './request';
import http from '@ohos.net.http';
import { fileManager } from "../utils/fileUtils"
import { promptAction } from '@kit.ArkUI';

let GENERATION_URL =
  "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=24.e422719def479f4d4ba50493400fac8a.2592000.1737641786.282335-116239425"
let TAG = "_:TranslateManager"

export default class TranslateManager {
  private result: string = ''
  private requestOptions: http.HttpRequestOptions = {}

  InitParam(q, from ,to) {
    this.requestOptions = {
      method: http.RequestMethod.POST,
      header: [{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }],
      extraData: JSON.stringify({
        "from": from,
        "to": to,
        "q": q
      }),
    }
  }

  parseResult(result) {
    let TAG = "_:[parseResult]"
    console.log(TAG, "rawresult is ", result)
    if (result.includes("error_msg")){
      promptAction.showToast({"message":result,"duration":5000})
    }
    try {
      let resultj = JSON.parse(result)
      let str = ""
      str = resultj["result"]["trans_result"][0]["dst"]
      return str
    } catch (e) {
      console.log(TAG, "parseResult", e)
      return result
    }
  }

  async Translate(word,from="auto",to="en"):Promise<string> {
    let TAG = "_:Translate"
    console.log(TAG, "entered with wordstr", word)
    let time1: Date = new Date();
    this.InitParam(word,from,to)
    console.log(TAG, JSON.stringify(this.requestOptions))
    return new Promise(resolve => {
      httpService.requestHttpWithOption(GENERATION_URL, this.requestOptions).then((data: http.HttpResponse) => {
        console.info(TAG, "send request sucess,the response is:" + JSON.stringify(data));
        let time2: Date = new Date();
        let costTime = time2.getTime() - time1.getTime();
        if (data.responseCode != 200 || data.responseCode == null) {
          this.result = '获取结果失败，请重试'
        } else {
          this.result = this.parseResult(data.result as string)
        }
        console.log(TAG, "llm costTime", costTime)
        resolve(this.result)
      }).catch((err: Error) => {
        console.info(TAG, 'error:' + JSON.stringify(err));
        resolve("")
      });
    })
  }
}